package com.student.liu.controller;

import com.alibaba.fastjson.JSONObject;
import com.student.liu.entity.User;
import com.student.liu.entity.UserReceiveraddress;
import com.student.liu.service.IUserService;
import com.student.liu.utils.TokenUtils;
import lombok.Data;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.xml.bind.ValidationException;
import java.util.Date;

/**
 * 用户类 控制器
 */
@RestController
public class UserController extends BaseController {

    @Resource
    IUserService userService;

    /**
     * 用户登录
     * @param param
     * @return
     */
    @PostMapping("login")
    public Object login(@Valid @RequestBody LoginParam param, BindingResult result) throws ValidationException {
        User user = new User(param.getUsername(), param.getPassword());
        Integer id = userService.login(user);
        Date issuedTime = new Date();
        Date expiresTime = new Date(issuedTime.getTime() + 1000 * 60 * 60 * 72);  //过期时间为72个小时
        JSONObject resultValue = new JSONObject();
        JSONObject sign = new JSONObject();
        sign.put("id", id);
        sign.put("role", "user");       //普通用户角色：user，管理员角色：admin
        resultValue.put("token", TokenUtils.generate(sign.toJSONString(), issuedTime, expiresTime));
        return success("登录成功", resultValue);
    }

    /**
     * 用户注册
     * @param userRegisterBody
     * @param result
     * @return
     */
    @PostMapping("register")
    public Object register(@Valid @RequestBody UserRegisterBody userRegisterBody, BindingResult result) {
        User user = new User(userRegisterBody.getUsername(), userRegisterBody.getPassword(),
                userRegisterBody.getNickname(), userRegisterBody.getSex());
        userService.register(user);
        return success("注册成功", null);
    }

    /**
     * 获取当前请求者信息
     * @return
     */
    @GetMapping("get")
    @PreAuthorize("hasRole('ROLE_user')")
    public Object get() {
        //从Security上下文对象中取出当前请求者的身份信息
        Integer userId = Integer.parseInt(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        return success(null, "身份信息：" + userId);
    }

    /**
     * 获取当前请求者信息
     * @param disableUserId 被禁用的用户ID
     * @return
     */
    @PostMapping("disableUser")
    @PreAuthorize("hasRole('ROLE_admin')")
    public Object disableUser(@RequestParam Integer disableUserId) {
        userService.disableUser(disableUserId);
        return success("禁用成功", null);
    }

    @GetMapping("getById/{id}")
    public Object getById(@PathVariable Integer id) {
        return success(null, userService.getById(id));
    }


    /**
     * 获取当前请求者信息,修改密码
     * @param
     * @return
     */
    @PostMapping("change")
    @PreAuthorize("hasRole('ROLE_user')")
    public Object disableUser(@Valid @RequestBody LoginParam param) throws ValidationException{
        userService.Change(param.getUsername(),param.getPassword());
        return success("修改成功", null);
    }

    /**
     * 获取当前请求者信息,确认密码
     * @param
     * @return
     */
    @PostMapping("determine")
    @PreAuthorize("hasRole('ROLE_user')")
    public Object determine(@Valid @RequestBody LoginParam param) throws ValidationException{
        if(userService.determine(param.getUsername(),param.getPassword()) == 0){
        return success("密码输入错误", false);
        }else {
            return success("密码正确", true);
        }
    }

    @Data
    static class LoginParam{
        @NotBlank(message = "用户名不能为空")
        private String username;
        @NotBlank(message = "密码不能为空")
        private String password;
    }

    /**
     * 注册参数 实体
     */
    @Data
    static class UserRegisterBody{
        @NotBlank(message = "请传递用户名")
        private String username;
        @NotBlank(message = "请传递密码")
        private String password;
        @NotBlank(message = "请传递昵称")
        private String nickname;
        @NotBlank(message = "请传递性别")
        private String sex;
    }



}
